import java.util.Arrays;

public class MyHeap {
    public int[] elem;
    public int usedSize;

    public MyHeap() {
        this.elem = new int[10];
    }

    //初始化
    public void init(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    //创建大根堆
    public void createHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            siftDown(parent, usedSize);
        }
    }

    //交换
    private void swap(int i, int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    //向下调整
    public void siftDown(int parent, int end) {
        int child = 2 * parent + 1;
        while (child < end) {
            //比较child和child+1的值，使child 的值为最大
            if (child + 1 < end && elem[child] < elem[child + 1]) {
                child++;
            }
            if (elem[child] > elem[parent]) {
                swap(child, parent);
                //继续往下调整
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    //加上一个数
    public void offer(int val) {
        if (isFull()) {
            elem = Arrays.copyOf(elem, 2 * elem.length);
        }
        elem[usedSize] = val;
        usedSize++;
        //从最后一个开始调整
        siftUp(usedSize - 1);
    }

    //向上调整
    public void siftUp(int child) {
        int parent = (child - 1) / 2;
        while (parent >= 0) {//包括=，说明包括根节点
            if (elem[child] > elem[parent]) {
                swap(child, parent);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }
    //删除
    public int poll(){
        if (isEmpty()) {
            return -1;
        }
        int old=elem[0];
        swap(0,usedSize-1);
        usedSize--;
        siftDown(0,usedSize);
        return old;
    }
    public boolean isEmpty(){
        return usedSize==0;
    }
}











